<template>
  <div>
    <div class="search">
    <input class="search-input" v-model="keyword" type="text" placeholder="输入城市名或拼音">
  </div>
    <div class="search-content" ref="search" v-show="isShow">
      <ul>
        <li v-for="item of list" class="border-bottom search-item" :key="item.id" @click="handleCityClick(item.name)">{{item.name}}</li>
        <li v-show="!list.length" class="border-bottom search-item">没有找到相关数据！</li>
      </ul>
    </div>
  </div>

</template>

<script>
import Bscroll from 'better-scroll'
import {mapMutations, useStore} from 'vuex'
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from "vue-router";
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  setup(props){
    const keyword = ref('')
    const list = ref([])
    let timer = true
    let isShow = ref(false)
    const router = useRouter()
    const store = useStore()
    const search = ref(null)
    function handleCityClick(city){
      store.commit('changeCity',city)
      router.push('/')
    }
    onMounted(()=>{
      new Bscroll(search.value, {
        click: true
      })
    })
    watch(keyword,(keyword,preKeyword)=>{
      if (timer) {
        timer = false
        if (keyword === '') {
          isShow.value = false
        } else {
          isShow.value = true
        }
        setTimeout(() => {
          const result = []
          for (let i in props.cities) {
            props.cities[i].forEach((value) => {
              if (value.spell.indexOf(keyword) > -1 ||
              value.name.indexOf(keyword) > -1) {
                result.push(value)
              }
            })
          }
          list.value = result
          timer = true
        }, 100)
      }
    
    })
    return {keyword,list,isShow,search,handleCityClick}
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .search
    height .72rem
    background $bgColor
    padding 0 .1rem
    .search-input
      box-sizing border-box
      padding 0 .1rem
      height .62rem
      line-height .62rem
      width 100%
      text-align center
      border-radius .06rem
      color #666
  .search-content
    overflow hidden
    position absolute
    top 1.58rem
    left 0
    right 0
    bottom 0
    background #fff
    z-index 1
    .search-item
      line-height .62rem
      padding-left .2rem
      color #666
      background #fff

</style>
